<template>
    <div class="app-container">
      <el-row :gutter="15" class="search-form">
        <el-col :span="4">
          <el-form-item label="区域">
            <el-select v-model="searchForm.areaCode" clearable placeholder="请选择区域" @change="onRegionChange" style="width: 150px;">
              <el-option
                v-for="region in areaList"
                :key="region.areaCode"
                :label="region.areaName"
                :value="region.areaCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="线路">

            <el-select v-model="searchForm.lineId" clearable placeholder="请选择线路"  style="width: 150px;">
              <el-option
                v-for="line in lineList"
                :key="line.id"
                :label="line.lineName"
                :value="line.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
       
        <el-col :span="4" class="buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <!-- <el-button type="warning" @click="handleReset">重置</el-button> -->
        </el-col>
      </el-row>


      <el-row :gutter="15" class="">
        <el-col :span="6">
          <el-form ref="elForm" :model="dataForm" :rules="rules" size="small" label-width="70px" label-position="right"
            :disabled="!!isDetail">

               <el-col :span="24">
              <el-form-item label="设备信息" prop="pointInfomation">
                <el-input v-model="dataForm.pointInfomation" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="地点" prop="kqLocation">
                <el-input v-model="dataForm.kqLocation" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                </el-input>
              </el-form-item>
            </el-col>
   
            <el-col :span="24">
              <el-form-item label="经度" prop="kqLongitude">
                <el-input v-model="dataForm.kqLongitude" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                </el-input>
              </el-form-item>
            </el-col>
   
            <el-col :span="24">
              <el-form-item label="纬度" prop="kqLatitude">
                <el-input v-model="dataForm.kqLatitude" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                </el-input>
              </el-form-item>
            </el-col>
   
         
          </el-form>
        </el-col>
        <el-col :span="18">
          <div style="width: 100%">
            <!-- <div class="search_box">
              <div class="label">关键字搜索</div>
              <el-input v-model="input" placeholder="请输入内容" id="tipinput"></el-input>
            </div> -->
            <div ref="gaode_Map" id="gaode_Map"></div>
          </div>
        </el-col>
      </el-row>
    </div>
</template>
<script>

  import AMapLoader from "@amap/amap-jsapi-loader";
  import { selectAllAreaList } from "@/api/line/area.js";
  import { selectAllLineList } from "@/api/line/line.js";
  import { selectAllElectricityPoleAndLineInfoList } from "@/api/line/pole.js";

  window._AMapSecurityConfig = {
    // 设置安全密钥
    securityJsCode: "cb0c4ee4cd056c0bb65a542fcf5e289c",
  };
  export default {
    name: "GaoDeMap",
    components: {},
    props: [],
    data () {
      return {
        loading: false,
        visible: false,
        isDetail: false,
        searchForm:{
          lineId:null,
          areaCode:'',
        },
        areaList:[],
        lineList:[],
        dataForm: {
          pointInfomation:null,
          kqName: undefined,
          kqLocation: undefined,
          kqLongitude: undefined,
          kqLatitude: undefined,
          kqWorkUnit: undefined,
          cronkqAccredit: [],
          kqValidCardRange: undefined,
        },
        rules: {},
        input: "",
        map: null,
        auto: null,
        placeSearch: null,
        lnglat: [],
        markers: [],
        position: {},
        blinkTimer:null,
      };
    },
    computed: {},
    watch: {
       
  },
    created () { 
        //DOM初始化完成进行地图初始化
        this.selectAllAreaList();
    },
    mounted () {
        //DOM初始化完成进行地图初始化
        
        const poleLongitude = this.$route.query.poleLongitude; 
        const poleLatitude = this.$route.query.poleLatitude; 
        const poleStatus = this.$route.query.poleStatus == '0' ? true : false; 
        const alarmInformation = this.$route.query.alarmInformation || ""; // 默认提示内容
        const content = this.$route.query.content || ""; // 默认提示内容
        this.initMap(poleLongitude,poleLatitude,alarmInformation,content,poleStatus);

     },
    methods: {
    /** 查询电杆信息列表 */
    /** 查询电杆信息列表 */
handleSearch() {
  selectAllElectricityPoleAndLineInfoList(this.searchForm).then(response => {
    const poleList = response.data || []; // 查询结果
    this.poleList = poleList;

    // 清空已有标记点
    this.removeMarker();

    if (poleList.length === 0) {
      this.$message.warning("未查询到结果");
      return;
    }

    // 设置地图的可视区域到第一条数据的坐标
    const firstPole = poleList[0];
    const { poleLongitude, poleLatitude } = firstPole;

    if (poleLongitude && poleLatitude) {
      this.map.setCenter([poleLongitude, poleLatitude]); // 设置地图中心点
    }

    // 遍历结果，添加标记点
    poleList.forEach(pole => {
      const latitude = pole.poleLatitude;
      const longitude = pole.poleLongitude;
      const alarmInformation = pole.alarmInformation;
      const content = pole.poleName;
      const poleStatus = pole.alarmStatus == '0' ? true : false;
      this.addMarker([longitude, latitude], alarmInformation, content, poleStatus);
    });
  });
},

//     handleSearch() {
//   selectAllElectricityPoleAndLineInfoList(this.searchForm).then(response => {
//     const poleList = response.data || []; // 查询结果
//     this.poleList = poleList;

//     // 清空已有标记点
//     this.removeMarker();
//     if (poleList.length === 0) {
//       this.$message.warning("未查询到结果");
//     }

//     // 遍历结果，添加标记点
//     poleList.forEach(pole => {
//       const latitude = pole.poleLatitude;
//       const longitude = pole.poleLongitude;
//       const alarmInformation = pole.alarmInformation;
//       const content =   pole.poleName;
//       const poleStatus = pole.alarmStatus == '0' ? true : false ;
//       const marker = this.addMarker([longitude, latitude],alarmInformation, content,poleStatus);
//     });


//   });
// },



addMarker(lnglat,alarmInformation, content,poleStatus) {
  const fontColor = poleStatus ? "black" : "green";
    var labelContent;
    var marker;
        if(fontColor == "black"){
          labelContent  = content
    ? `<div style="background-color: white; padding: 8px 10px; border-radius: 4px; font-size: 16px; line-height: 24px; outline: none; display: flex; flex-direction: column; align-items: center; justify-content: center;">
  <div style="display: flex; align-items: center; color: red; margin-bottom: 5px; justify-content: center;">
    <!-- 红底圆圈，中央一根白杠，直径与字体高度一致 -->
    <span style="
      display: inline-block; 
      width: 16px; 
      height: 16px; 
      background-color: red; 
      border-radius: 50%; 
      position: relative; 
      margin-right: 5px; 
      outline: none;">
      <span style="
        display: inline-block; 
        width: 10px; 
        height: 3px; 
        background-color: white; 
        position: absolute; 
        top: 50%; 
        left: 50%; 
        transform: translate(-50%, -50%); 
        outline: none;">
      </span>
    </span>
    <span style="outline: none;">${alarmInformation}</span>
  </div>
  <div style="color: black; outline: none; text-align: center; line-height: 24px;">
    ${content}<br>
    温度已超过正常值
  </div>
</div>
`
    : null;
    marker = new AMap.Marker({
    position: lnglat,
    label: {
      content: labelContent,
      direction: "top",
      offset: new AMap.Pixel(0, 0),
      
    },
  });
        }else{
          marker = new AMap.Marker({
    position: lnglat
  });
        }



  marker.setMap(this.map);
  this.markers.push(marker); // 保存标记引用
  return marker; // 返回标记实例
},




removeMarker() {
  if (this.markers.length) {
    this.markers.forEach(marker => marker.setMap(null));
    this.markers = [];
  }
  if (this.blinkTimer) {
        clearInterval(this.blinkTimer); // 清除定时器
        this.blinkTimer = null;
      }
},

      /** 选择区域触发 */
      onRegionChange(value) {
  return new Promise((resolve) => {
    const queryParams = { areaCode: value };
    selectAllLineList(queryParams).then(response => {
      this.lineList = response.data;
      this.searchForm.lineId = null; // 清空已选中的线路
      resolve();
    });
  });
},
      /** 查询所有区域 */
      selectAllAreaList(){
      selectAllAreaList().then(response => {
        this.areaList = response.data;
      });
    },



      // 地图初始化
      initMap(longitude, latitude,alarmInformation,content,poleStatus)  {
        this.removeMarker(); // 清除标记
        let centerLen = [104.691113, 30.119187];
        if(longitude!=null && latitude != null){
            centerLen = [longitude, latitude];
        }
        
        AMapLoader.load({
          key: "e5a1cf75da8cc70879aafcc5d84e14b2", // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
        })
          .then((AMap) => {
            this.map = new AMap.Map("gaode_Map", {
              // 设置地图容器id
              viewMode: "3D", //  是否为3D地图模式
              zoom: 18, // 初始化地图级别
              center: centerLen, //中心点坐标
              resizeEnable: true,
            });
            this.setMarker(centerLen,alarmInformation,content,poleStatus);
            this.getLocationAddress(centerLen);
            // 关键字查询
            // this.searchMap();
            // 监听鼠标点击事件
            // this.map.on("click", this.clickMapHandler);
          })
          .catch((e) => { });
      },
      // 关键字查询
      searchMap () {
        // 搜索框自动完成类
        this.auto = new AMap.AutoComplete({
          input: "tipinput", // 使用联想输入的input的id
        });
        //构造地点查询类
        this.placeSearch = new AMap.PlaceSearch({
          map: this.map,
        });
        // 当选中某条搜索记录时触发
        this.auto.on("select", this.selectSite);
      },
    

            // 根据经纬度，并添加标记
      getLocationAddress (centerLen) {

        debugger
        this.dataForm.kqLongitude = centerLen[0];
        this.dataForm.kqLatitude = centerLen[1];
    
        debugger
        // 点击地图上的位置，根据经纬度转换成详细地址
        let geocoder = new AMap.Geocoder({});
        let that = this;
        debugger
        geocoder.getAddress(centerLen, function (status, result) {
          
            that.dataForm.kqLocation = result.regeocode.formattedAddress;

        });
        this.position = {
          longitude: kqLongitude,
          latitude: kqLatitude,
          address: that.address,
        };
        this.input = that.address; //把查询到的地址赋值到输入框
        this.lnglat = [kqLongitude, kqLatitude];
      },
      //  添加标记
      setMarker (lnglat,alarmInformation,content,poleStatus) {
        
         const backgroundColor = poleStatus ? "white" : "green";
         if (this.blinkTimer) {
          clearInterval(this.blinkTimer); // 清除之前的闪烁定时器
          }
        this.removeMarker();
        var lableContent;
        if(backgroundColor == "white"){
          lableContent = content == '' ? null:`<div style="background-color: white; padding: 8px 10px; border-radius: 4px; font-size: 16px; line-height: 24px; outline: none; display: flex; flex-direction: column; align-items: center; justify-content: center;">
  <div style="display: flex; align-items: center; color: red; margin-bottom: 5px; justify-content: center;">
    <!-- 红底圆圈，中央一根白杠，直径与字体高度一致 -->
    <span style="
      display: inline-block; 
      width: 16px; 
      height: 16px; 
      background-color: red; 
      border-radius: 50%; 
      position: relative; 
      margin-right: 5px; 
      outline: none;">
      <span style="
        display: inline-block; 
        width: 10px; 
        height: 3px; 
        background-color: white; 
        position: absolute; 
        top: 50%; 
        left: 50%; 
        transform: translate(-50%, -50%); 
        outline: none;">
      </span>
    </span>
    <span style="outline: none;">${alarmInformation}</span>
  </div>
  <div style="color: black; outline: none; text-align: center; line-height: 24px;">
    ${content}<br>
    温度已超过正常值
  </div>
</div>`;
                    this.dataForm.pointInfomation = content;
        let marker = new AMap.Marker({
          position: lnglat,
          label: {
          content: lableContent,
          direction: "top", // 显示在标记的上方
          offset: new AMap.Pixel(0, 0), // 偏移量
        },
        });
        marker.setMap(this.map);
        this.markers.push(marker);
                    
        }else{
          lableContent = ''
          this.dataForm.pointInfomation = content;
        let marker = new AMap.Marker({
          position: lnglat
        });
        marker.setMap(this.map);
        this.markers.push(marker);
        }

        this.dataForm.pointInfomation = content;
        let marker = new AMap.Marker({
          position: lnglat,
          label: {
          content: lableContent,
          direction: "top", // 显示在标记的上方
          offset: new AMap.Pixel(0, 0), // 偏移量
        },
        });
        marker.setMap(this.map);
        this.markers.push(marker);
      },

      // 删除之前后的标记点
      // removeMarker () {
      //   if (this.markers) {
      //     this.map.remove(this.markers);
      //   }
      //   if (this.blinkTimer) {
      //   clearInterval(this.blinkTimer); // 清除定时器
      //   this.blinkTimer = null;
      // }
      // },
    },

  //   beforeDestroy() {
  //   // 组件销毁时清理资源
  //   this.clearMarker();
  //   if (this.map) {
  //     this.map.destroy();
  //     this.map = null;
  //   }
  // },

  beforeDestroy() {
  this.removeMarker();
  if (this.map) {
    this.map.destroy();
    this.map = null;
  }
}

  };
  </script>
   
   
  <style lang="scss">
  .search_box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 50px;
   
    .label {
      color: #000;
      width: 100px;
    }
  }
   
  .content {
    position: relative;
  }
   
  #panel {
    position: absolute;
    top: 50px;
    right: 20px;
  }
   
  #gaode_Map {
    overflow: hidden;
    width: 100%;
    height: 540px;
    margin: 0;
  }
   
  .amap-sug-result {
    z-index: 2999 !important;
  }
  </style>